package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.base.result.ResponseVo;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.base.util.SrbAssert;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 借款信息表 前端控制器
 * </p>
 *
 * @author muzhao
 * @since 2024-08-19
 */
@RestController
@RequestMapping("/api/core/borrowInfo")
public class ApiBorrowInfoController {
    @Resource
    BorrowInfoService borrowInfoService;

    @ApiOperation("撤销借款申请")
    @PutMapping("myBorrows/{id}")
    public ResponseVo borrowCancel(@PathVariable Long id,
                                   @RequestHeader(value = "token") String token) {
        Long userId = JwtUtils.getUserId(token);
        //校验借款申请的状态 只有待审核的才可以撤销
        boolean flag = borrowInfoService.update(Wrappers.lambdaUpdate(BorrowInfo.class)
                .eq(BorrowInfo::getId, id)
                .eq(BorrowInfo::getUserId, userId)
                .eq(BorrowInfo::getStatus, 1)//查询登录的用户的指定的状态为待审核的借款信息
                .set(BorrowInfo::getStatus, -2));//更新状态为撤销状态
        SrbAssert.assertTrue(flag, ResponseEnum.USER_BORROWINFO_STATUS_ERROR);
        return ResponseVo.ok().message("撤销成功");
    }

    @ApiOperation("查询借款记录列表")
    @GetMapping("myBorrows/{pageNum}/{pageSize}")
    public ResponseVo myBorrows(@RequestHeader(value = "token") String token,
                                @PathVariable("pageNum") Integer pageNum,
                                @PathVariable("pageSize") Integer pageSize) {
        Page<BorrowInfo> page = new Page<>(pageNum, pageSize);
        borrowInfoService.getMyBorrows(page, token);
        return ResponseVo.ok().data("page", page);
    }

    @ApiOperation("贷款申请")
    @PostMapping
    public ResponseVo sava(@RequestBody BorrowInfo borrowInfo,
                           @RequestHeader(value = "token") String token) {
        borrowInfoService.saveApply(borrowInfo, token);
        return ResponseVo.ok();
    }

}

